import Taro, { Component } from "@tarojs/taro";
import { View, Input, Text, Image, ScrollView } from "@tarojs/components";
import { getSearchTags, searchTaskForTag } from "../../actions/task";
import { connect } from "@tarojs/redux";
import { AtIcon } from "taro-ui";
import { setCache, getCache } from "../../utils/cache";
import Item from "../../components/task/item";
import { TAG_HISTORY } from "../../service/config";
import "./search.less";

@connect(
  ({ task }) => ({ ...task }),
  dispatch => ({
    async getSearchTags() {
      dispatch(await getSearchTags());
    },
    async searchTaskForTag(params) {
      dispatch(await searchTaskForTag(params));
    }
  })
)
class Search extends Component {
  config = {
    navigationBarTitleText: "搜索"
  };

  state = {
    key: "",
    showList: false,
    page: 1,
    historyTags: getCache(TAG_HISTORY)
  };

  async componentWillMount() {
    await this.props.getSearchTags();
  }

  async searchTaskForKey() {
    const { key, page } = this.state;
    if (key === "") {
      Taro.showToast({
        title: "请输入搜索关键字",
        icon: "none",
        duration: 2000
      });
      return false;
    }
    await this.props.searchTaskForTag({ key, page });
    this.setState({
      showList: true
    });
    let history =
      getCache(TAG_HISTORY) instanceof Object &&
      Object.keys(getCache(TAG_HISTORY)).length === 0
        ? []
        : getCache(TAG_HISTORY);

    history.push(key);
    let set = new Set(history);
    let arr = Array.from(set);
    setCache(TAG_HISTORY, arr);
  }

  handleOnScrollToUpper() {
    const { key } = this.state;
    this.setState(
      {
        page: 1
      },
      async () => {
        await this.props.searchTaskForTag({ key, page: 1 });
      }
    );
  }

  handleOnScrollToLower() {
    const { key, page } = this.state;
    this.setState(
      {
        page: page + 1
      },
      async () => {
        await this.props.searchTaskForTag({ key, page: this.state.page });
      }
    );
  }

  render() {
    const clientHeight = document.getElementById("app").clientHeight - 105;
    const { tags, search_list } = this.props;
    const { showList, historyTags } = this.state;
    return (
      <View className="search-index">
        <View className="search-head">
          <Image
            className="search-back-icon"
            onClick={() => {
              Taro.navigateBack();
            }}
            src={require("../../assets/img/back.png")}
          />
          <View className="search-bar">
            <View className="search-icon">
              <AtIcon value="search" size="20" color="#409EFF" />
            </View>
            <View className="search-input">
              <Input
                type="text"
                placeholder="搜索"
                value={this.state.key}
                onInput={e => {
                  this.setState({
                    key: e.target.value
                  });
                }}
                focus
              />
            </View>
          </View>
          <View
            className="search-btn"
            onClick={this.searchTaskForKey.bind(this)}
          >
            搜索
          </View>
        </View>
        <View className="body-con">
          <View className="search-recommended">
            {tags.map(item => (
              <View
                className="redommended-item"
                onClick={() => {
                  Taro.redirectTo({
                    url:
                      "/pages/index/task?id=" + item.id + "&type=" + item.type
                  });
                }}
              >
                {item.name}
              </View>
            ))}
          </View>
          {historyTags.length > 0 && !showList && (
            <View className="search-body">
              <View className="search-history-head">
                <Text className="history-title">搜索历史</Text>
                <Image
                  className="history-del-img"
                  src={require("../../assets/img/del.png")}
                />
              </View>
              <View className="search-history-record">
                {historyTags.map((item, index) => (
                  <View
                    className="history-record-item"
                    onClick={() => {
                      this.setState({
                        key: item
                      });
                    }}
                    key={index}
                  >
                    {item}
                  </View>
                ))}
              </View>
            </View>
          )}
          {showList && (
            <View className="product-list">
              <ScrollView
                className="container"
                scrollY
                scrollWithAnimation
                style={{ height: clientHeight + "px" }}
                scrollTop="0"
                lowerThreshold="10"
                onScrollToUpper={this.handleOnScrollToUpper.bind(this)}
                onScrollToLower={this.handleOnScrollToLower.bind(this)}
              >
                {search_list.length > 0 ? (
                  [
                    search_list.map((item, index) => (
                      <View style="margin:10px;border-radius:5px;box-shadow: 0 2px 4px 2px rgba(235,235,235,0.50);">
                        <Item item={item} index={index} />
                      </View>
                    )),
                    search_list.length % 10 > 0 && (
                      <View style="display:flex;flex-direction:row;justify-content:center">
                        <Text style="font-size:12px;color:#cccccc;">
                          -没有更多了-
                        </Text>
                      </View>
                    )
                  ]
                ) : (
                  <View className="have-no-data">
                    <Text style="font-size:12px;color:#cccccc;">
                      - 暂无数据 -
                    </Text>
                  </View>
                )}
              </ScrollView>
            </View>
          )}
        </View>
      </View>
    );
  }
}
export default Search;
